package com.chaos.eurekaproducer.delayQueue;

import lombok.Data;
import lombok.EqualsAndHashCode;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @author liaopeng
 * @title: MyDelayed
 * @projectName eureka-producer
 * @description: 自定义实体类实现Delayed接口，并实现其两个方法
 * @date 2021/8/16下午5:32
 */
@Data
@EqualsAndHashCode
public class MyDelayEntity implements Delayed {

    private Long id;

    private Long startTime;//时间戳

    public MyDelayEntity(Long id, Long startTime) {
        this.id = id;
        this.startTime = startTime;
    }
    /**
     * 定义了剩余到期时间
     * 超时判定是通过getDelay(TimeUnit.NANOSECONDS)方法的返回值小于等于0来判断
     * @param unit
     * @return
     */
    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(startTime - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }

    /**
     * 确定队列里的元素排序
     * @param o
     * @return
     */
    @Override
    public int compareTo(Delayed o) {
        if (o == this) {
            return 0;
        }
        if (o instanceof MyDelayEntity) {
            MyDelayEntity otherRequest = (MyDelayEntity) o;
            long otherStartTime = otherRequest.getStartTime();
            return (int) (this.startTime - otherStartTime);
        }
        return 0;
    }
}
